package lucene.server.web.controller.admin;


import lombok.extern.slf4j.Slf4j;
import lucene.server.common.utils.StringUtil;
import lucene.server.core.LuceneService;
import lucene.server.core.model.FieldConfig;
import lucene.server.core.model.IndexConfig;
import lucene.server.database.DBMetaService;
import lucene.server.web.LuceneServerInit;
import lucene.server.web.config.LuceneConfig;
import lucene.server.web.config.SystemConfig;
import lucene.server.web.dao.DynamicDataSource;
import lucene.server.web.dao.IndexConfigDao;
import lucene.server.web.dao.SystemDao;
import lucene.server.web.model.ConnConfig;
import lucene.server.common.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/admin/setting")
@Slf4j
public class SettingController {
    @Autowired
    private LuceneServerInit luceneServerInit;

    /**
     *
     * */
    @GetMapping(value = "/getSetting")
    public Result<?> getSetting(HttpServletRequest req) throws SQLException {
        List<IndexConfig> indexConfigList = (List<IndexConfig>) SystemDao.getAll("index_config", IndexConfig.class);
        List<FieldConfig> fieldConfigList = (List<FieldConfig>) SystemDao.getAll("index_field", FieldConfig.class);
        for (IndexConfig indexConfig : indexConfigList){
            for (FieldConfig fieldConfig : fieldConfigList){
                if (indexConfig.getName().equals(fieldConfig.getIndexName())){
                    indexConfig.getFieldsConfig().add(fieldConfig);
                }
            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put("index", indexConfigList);
        map.put("indexRoot", SystemConfig.getIndexRoot());
        return  Result.OK(map);
    }
    /**
     *
     * */
    @PostMapping(value = "/updateSetting")
    public Result<?> updateSetting(@RequestBody IndexConfig indexConfig, HttpServletRequest req  ) throws SQLException {
       //如果是新的索引配置，先判断是否存在同名
       if (indexConfig.getId()==null && SystemDao.checkExists(indexConfig, "name")) {
            return Result.error("索引名称已存在");
       }
       String error =  IndexConfigDao.checkConfig(indexConfig);
       if (!StringUtil.isEmpty(error)){
           return Result.error(error);
       }

       if(StringUtil.isNotEmpty(indexConfig.getId())){
           IndexConfig oldConfig = SystemDao.findOne(indexConfig, IndexConfig.class);
           luceneServerInit.shutdownOne(oldConfig.getName());
       }
       IndexConfigDao.insertIndex(indexConfig);
       luceneServerInit.runOne(indexConfig.getName());
       return  Result.OK( );
    }
    /**
     *
     * */
    @PostMapping(value = "/deleteSetting")
    public Result<?> deleteSetting(@RequestBody IndexConfig indexConfig, HttpServletRequest req  ) throws SQLException {
        //删除数据库配置
        IndexConfigDao.deleteIndex(indexConfig);
        LuceneService.deleteIndex(indexConfig.getName());
        luceneServerInit.shutdownOne(indexConfig.getName());
        return  Result.OK();
    }
    /**
     *
     * */
    @GetMapping(value = "/getRuntimeConfig")
    public Result<?> getRuntimeConfig(@RequestParam(name = "indexName",required = false)  String indexName,HttpServletRequest req) throws SQLException {

        return  Result.OK( LuceneConfig.getIndexConfigs());
    }
    /**
     *
     * */
    @GetMapping(value = "/getSchema")
    public Result<?> getSchema(
            @RequestParam(name = "conn",required = false)  String conn,
            @RequestParam(name = "database",required = false)  String database,
            @RequestParam(name = "table",required = false) String table) throws SQLException {

        Map<String,Object> map = new HashMap<>();
        if (!StringUtil.isEmpty(conn)  && !StringUtil.isEmpty(database) && !StringUtil.isEmpty(table)){
            ConnConfig connConfig = DynamicDataSource.getConnConfig(conn);
            map.put("type", "fields");
            map.put("data", DBMetaService.getColumns(conn,connConfig.getConnType(),database,table));
        }else if (!StringUtil.isEmpty(conn)&& !StringUtil.isEmpty(database) && StringUtil.isEmpty(table)){
            ConnConfig connConfig = DynamicDataSource.getConnConfig(conn);
            map.put("type", "table");
            map.put("data", DBMetaService.getTables(conn,connConfig.getConnType(),database));
        }else if (!StringUtil.isEmpty(conn)&& StringUtil.isEmpty(database)){
            ConnConfig connConfig = DynamicDataSource.getConnConfig(conn);
            map.put("type", "database");
            map.put("data", DBMetaService.getDatabases(conn,connConfig.getConnType()));
        }else {
            map.put("type", "conn");
            map.put("data", SystemDao.getAll("conn", ConnConfig.class));
        }
        return  Result.OK(map);
    }

}

